<template>
  <div ref="container" class="vue-bpmn-diagram-container"></div>
</template>

<script>
  import BpmnJS from 'bpmn-js/dist/bpmn-navigated-viewer.production.min.js'

  export default {
    name: 'vue-bpmn',
    props: {
      url: {
        type: String,
        required: false
      }
    },
    data () {
      return {
        diagramXML: null
      }
    },
    mounted () {
      var container = this.$refs.container

      var self = this

      this.bpmnViewer = new BpmnJS({
        container: container
      })

      this.bpmnViewer.on('import.done', function (event) {
        var error = event.error
        var warnings = event.warnings
        if (error) {
          self.$emit('error', error)
        } else {
          self.$emit('shown', warnings)
        }

        self.bpmnViewer.get('canvas').zoom('fit-viewport')
      })

      if (this.url) {
        this.fetchDiagram(this.url)
      }
    },
    beforeDestroy () {
      this.bpmnViewer.destroy()
    },
    watch: {
      url (val) {
        this.$emit('loading')
        this.fetchDiagram(val)
      },
      diagramXML (val) {
        this.bpmnViewer.importXML(val)
      }
    },
    methods: {
      fetchDiagram (url) {
        var self = this
        this.$http({
          url: this.$http.adornUrl(url),
          method: 'get',
          params: this.$http.adornParams({})
        }).then(({data}) => {
          if (data) {
            self.diagramXML = data
          }
        })
      },
      importXML (text) {
        this.bpmnViewer.importXML(text)
      },
      highlight (id) {
        var canvas = this.bpmnViewer.get('canvas')
        canvas.addMarker(id, 'highlight')
        document.querySelector('[data-element-id="' + id + '"]>.djs-outline').setAttribute('rx', '14px')
        document.querySelector('[data-element-id="' + id + '"]>.djs-outline').setAttribute('ry', '14px')
      }
    }
  }
</script>

<style>
  .vue-bpmn-diagram-container {
  	position: absolute;
    height: 72%;
    width: 95%;
  }
.djs-element.highlight .djs-outline {
  stroke: #8888FF;
  stroke-width: 2px;
  visibility: visible
}
</style>
